const Terser = require('terser');
const fs = require('fs');
const path = require('path');

// 压缩函数
async function minifyFile(filePath, outputPath) {
  try {
    const data = fs.readFileSync(filePath, 'utf8');
    const result = await Terser.minify(data, {
      compress: {
        // 启用所有标准压缩选项
        drop_console: true,  // 删除 console.log 语句
        pure_funcs: ['console.info', 'console.debug'],  // 删除指定的函数调用
      },
      mangle: true,         // 启用变量名混淆
      format: {
        // 通过下面的选项控制输出格式
        comments: false,  // 删除注释
      },
      toplevel: true,      // 启用顶级变量混淆
    });
    if (result.error) throw result.error;
    fs.writeFileSync(outputPath, result.code, 'utf8');
    console.log(`Minified: ${filePath}`);
  } catch (error) {
    console.error(`Failed to minify ${filePath}: ${error.message}`);
  }
}

// 遍历并压缩文件
function compressDirectory(dir) {
  if (!fs.existsSync(dir)) {
    console.error(`Directory not found: ${dir}`);
    return;
  }

  fs.readdirSync(dir).forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      compressDirectory(filePath);
    } else if (file.endsWith('.mjs')) {
      const outputPath = filePath.replace('.mjs', '.mjs');
      minifyFile(filePath, outputPath);
    }
  });
}

// 压缩 dist/ngx-raw-ui/esm2022 和 dist/ngx-raw-ui/fesm2022 目录下的文件
compressDirectory(path.join(__dirname, 'dist/ngx-raw-ui/esm2022'));
compressDirectory(path.join(__dirname, 'dist/ngx-raw-ui/fesm2022'));
